﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.App.Data;
using System.Data;

namespace LiMinCRMPlugin
{
    /// <summary>
    /// 生产月计划 下推预测单     2024年7月17日10:55:37 mey  
    /// </summary>
    [Description("单据转换插件:生产月计划 下推预测单 隔月")]
    [HotUpdate]
    public class GYMonProductionPlanToForecAst : AbstractConvertPlugIn
    {
        private object fid;
        private string fentryid;
        private List<string> _listDetailId = new List<string>(); //存储过滤条件后的单据体内码


        public override void OnGetSourceData(GetSourceDataEventArgs e)
        {
            base.OnGetSourceData(e);

            fid = e.SourceData[0]["Fid"];
            for (int i = 0; i < e.SourceData.Count; i++)
            {
                fentryid = fentryid + "," + e.SourceData[i]["FEntity_FEntryID"];

            }


        }

        public override void OnAfterFieldMapping(AfterFieldMappingEventArgs e)
        {
            fentryid = "123" + fentryid;
            base.OnAfterFieldMapping(e);
            ExtendedDataEntity[] billHead = e.TargetExtendDataEntitySet.FindByEntityKey("FBillHead"); //预测单
            object[] obs = new object[1];
            obs[0] = fid;
            var BillMeta =
                MetaDataServiceHelper.Load(this.Context, "RDLV_MonProductionPlan") as FormMetadata;   // 生产计划单



            string str = string.Format(@"/*dialect*/ select * from RDLV_t_MonProductionPlan a,RDLV_t_MonProductionPlanE b where a.fid=b.fid and fentryid in(" + fentryid + ")");

            DynamicObjectCollection obj = DBServiceHelper.ExecuteDynamicObject(this.Context, str);

            for (int k = 0; k < billHead.Count(); k++) //生成几个预测单
            {
                SetData(billHead[k], e.TargetBusinessInfo, obj, BillMeta.BusinessInfo, k);
            }
        }

        private void SetData(ExtendedDataEntity billHead, BusinessInfo businessInfo, DynamicObjectCollection obj, BusinessInfo srcBusinessInfo, int a)
        {

            DynamicObjectCollection entityCollection = billHead.DataEntity["PLN_FORECASTENTRY"] as DynamicObjectCollection; //预测单明细



            DynamicObjectCollection srcCollection = obj; //生产计划--明细


            DateTime dateTime = Convert.ToDateTime(obj[0]["F_RDLV_Year"].ToString() + "-" + obj[0]["F_RDLV_Month"].ToString() + "-01").AddHours(1);


            int year = dateTime.Year;
            int month1 = dateTime.Month;





            entityCollection.Clear();

            #region  赋值  单据体
            int EntryCount = Convert.ToInt32(srcCollection.Count); //生产计划总行数
            for (int i = 0; i < EntryCount; i++)
            {
                for (int j = 0; j < 1; j++)
                {
                    DynamicObject dyo_Allocation = new DynamicObject(entityCollection.DynamicCollectionItemPropertyType);
                    dyo_Allocation["seq"] = i+1;//* 4 + j + 1

                    string ProOrgId_Id = srcCollection[i]["F_RDLV_ProOrgId"].ToString();//组织
                    //预测组织
                    if (!ProOrgId_Id.EqualsIgnoreCase("0"))
                    {
                        dyo_Allocation["SupplyOrgId_Id"] = ProOrgId_Id;
                        dyo_Allocation["SupplyOrgId"] = BusinessDataServiceHelper.LoadSingle(this.Context, ProOrgId_Id,
                            (businessInfo.GetField("FSupplyOrgId") as BaseDataField).RefFormDynamicObjectType);


                    }
                    //库存组织                                                                   //预测组织
                    if (!ProOrgId_Id.EqualsIgnoreCase("0"))
                    {
                        dyo_Allocation["StockOrgId_Id"] = ProOrgId_Id;
                        dyo_Allocation["StockOrgId"] = BusinessDataServiceHelper.LoadSingle(this.Context, ProOrgId_Id,
                            (businessInfo.GetField("FStockOrgId") as BaseDataField).RefFormDynamicObjectType);


                    }

                    dyo_Allocation["OwnerTypeId"] = "BD_OwnerOrg";//货主类型

                    if (!ProOrgId_Id.EqualsIgnoreCase("0"))//货主
                    {
                        dyo_Allocation["OwnerId_Id"] = ProOrgId_Id;
                        dyo_Allocation["OwnerId"] = BusinessDataServiceHelper.LoadSingle(this.Context, ProOrgId_Id,
                            (businessInfo.GetField("FOwnerId") as BaseDataField).RefFormDynamicObjectType);


                    }

                    string Product_Id = srcCollection[i]["F_RDLV_Product"].ToString();//产品
                    //产品
                    if (!Product_Id.EqualsIgnoreCase("0"))
                    {
                        dyo_Allocation["MaterialID_Id"] = Product_Id;
                        dyo_Allocation["MaterialID"] = BusinessDataServiceHelper.LoadSingle(this.Context, Product_Id,
                            (businessInfo.GetField("FMaterialID") as BaseDataField).RefFormDynamicObjectType);


                    }


                    //BOM
                    //FBomID

                    string sql = @"/*dialect*/select FID from T_ENG_BOM where F_dev_normal='1' and FForbidStatus='A' " +
                        "and FDocumentStatus='C' and FUseOrgId='" + ProOrgId_Id + "' and FMATERIALID='" + Product_Id + "' order by FApproveDate desc";//

                    DataTable dt = DBUtils.ExecuteDataSet(Context, sql).Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {

                        dyo_Allocation["BomID_Id"] = dt.Rows[0][0];
                        dyo_Allocation["BomID"] = BusinessDataServiceHelper.LoadSingle(this.Context, dt.Rows[0][0],
                            (businessInfo.GetField("FBomID") as BaseDataField).RefFormDynamicObjectType);



                    }


                    string Unit_Id = srcCollection[i]["F_RDLV_Unit"].ToString();//单位
                    //单位
                    if (!Unit_Id.EqualsIgnoreCase("0"))
                    {
                        dyo_Allocation["UnitID_Id"] = Unit_Id;
                        dyo_Allocation["UnitID"] = BusinessDataServiceHelper.LoadSingle(this.Context, Unit_Id,
                            (businessInfo.GetField("FUnitID") as BaseDataField).RefFormDynamicObjectType);


                    }




                    string BaseUnit_Id = srcCollection[i]["F_RDLV_BaseUnit"].ToString();//基本单位
                                                                                        //基本单位
                    if (!Product_Id.EqualsIgnoreCase("0"))
                    {
                        dyo_Allocation["BaseUnitID_Id"] = BaseUnit_Id;
                        dyo_Allocation["BaseUnitID"] = BusinessDataServiceHelper.LoadSingle(this.Context, BaseUnit_Id,
                            (businessInfo.GetField("FBaseUnitID") as BaseDataField).RefFormDynamicObjectType);


                    }
                    decimal Qty1 = Convert.ToDecimal(srcCollection[i]["F_RDLV_MonthQty"]);//周期1
                    dyo_Allocation["Qty"] = Qty1;
                    dyo_Allocation["StartDate"] = year + "-" + month1 + "-01";
                    int CountDay = DateTime.DaysInMonth(year, month1);//获取月份的总天数
                    dyo_Allocation["EndDate"] = year + "-" + month1 + "-" + CountDay;


                  

                    dyo_Allocation["AveraCycle"] = 1; //均化

                 
                    dyo_Allocation["ReserveType"] = "1";//预留类型
                    dyo_Allocation["FCloseStatus"] = "A";//关闭状态


                    entityCollection.Add(dyo_Allocation);
                }
            }
            #endregion
        }
    }
}